package com.suishoupai.xmb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.suishoupai.xmb.entity.*;
import com.suishoupai.xmb.service.CategoryService;
import com.suishoupai.xmb.service.GoodsService;
import com.suishoupai.xmb.service.QiniuService;
import com.suishoupai.xmb.utils.PageUtil;
import com.suishoupai.xmb.utils.SecurityUserUtil;
import com.suishoupai.xmb.utils.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.util.Map;


/**
 * Created by caojian on 2017/3/10.
 */
@Controller
@RequestMapping("/sale/goods")
public class SaleGoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private QiniuService qiniuService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 商家的商品列表
     *
     * @return
     */
    @GetMapping("")
    @PreAuthorize("hasRole('ROLE_SALE')")
    public Object ownGoods(@RequestParam Map map, Model model) {
        long saleId = SecurityUserUtil.getUser().getId();
        PageUtil.startPage(map);
        Page page = (Page) goodsService.getGoodsBySaleId(saleId);
        model.addAttribute("goodsList", page.toPageInfo());
        return "sale-goods-list";
    }

    /**
     * 商品添加页面
     *
     * @param model
     * @return
     */
    @GetMapping("/add")
    @PreAuthorize("hasRole('ROLE_SALE')")
    public Object addPage(Model model) {
        long saleId = SecurityUserUtil.getUser().getId();
        model.addAttribute("categoryList", categoryService.getListBySaleId(saleId));
        return "goods-add";
    }

    /**
     * 商品上传token
     *
     * @return
     */
    @GetMapping("/uploadToken")
    @PreAuthorize("hasRole('ROLE_SALE')")
    @ResponseBody
    public Object uploadToken() {
        long saleId = SecurityUserUtil.getUser().getId();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uptoken", qiniuService.buildGoodsUploadToken(saleId));
        return jsonObject.toJSONString();
    }

    /**
     * 上传成功后，七牛回调
     *
     * @param goods
     * @return
     */
    @PostMapping("")
    @PreAuthorize("permitAll()")
    @ResponseBody
    public Object add(Goods goods) {
        ValidateUtil.isNull(goods.getSalesVolume());
        String imageKey = qiniuService.buildImageKey();
        goods.setImageKey(imageKey);
        goodsService.add(goods);
        return AjaxQiniuMessage.newSuccess(imageKey, AjaxMessage.newSuccessMsg(goods)).toJsonString();
    }

    /**
     * 商品详情
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ROLE_SALE')")
    public Object details(@PathVariable("id") long id, Model model) {
        model.addAttribute("cutGoods", goodsService.getGoodsById(id));
        long saleId = SecurityUserUtil.getUser().getId();
        model.addAttribute("downDomain", qiniuService.getDownDomain());
        model.addAttribute("categoryList", categoryService.getListBySaleId(saleId));
        return "goods-edit";
    }

    /**
     * 修改商品
     *
     * @param id
     * @param goods
     * @return
     */
    @PostMapping("/{id}")
    @PreAuthorize("hasRole('ROLE_SALE')")
    public Object update(@PathVariable("id") long id, Goods goods) {
        goods.setId(id);
        ValidateUtil.isNull(goods.getSaleId());
        ValidateUtil.isNull(goods.getImageKey());
        ValidateUtil.isNull(goods.getSalesVolume());
        ValidateUtil.in(goods.getStatus(), null, GoodsStatusEnum.SHELVES.getValue(), GoodsStatusEnum.OFF_SHELVES.getValue());
        goodsService.update(goods);
        return new ModelAndView(new RedirectView(id + "", true, false, true));
    }

    /**
     * 商品封面图修改token
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}/modifyToken")
    @PreAuthorize("hasRole('ROLE_SALE')")
    @ResponseBody
    public Object modifyToken(@PathVariable("id") long id) {
        CutGoods cutGoods = goodsService.getGoodsById(id);
        long saleId = SecurityUserUtil.getUser().getId();
        if (cutGoods.getGoods().getSaleId() != saleId) {
            return "";
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uptoken", qiniuService.buildGoodsModifyToken(id));
        return jsonObject.toJSONString();
    }

    /**
     * 封面图上传成功，七牛回调
     *
     * @param id
     * @return
     */
    @PostMapping("/{id}/coverImage")
    @PreAuthorize("permitAll()")
    @ResponseBody
    public Object updateCoverImage(@PathVariable("id") long id) {
        CutGoods cutGoods = goodsService.getGoodsById(id);
        if (!qiniuService.deleteKey(cutGoods.getGoods().getImageKey())) {
            throw new RuntimeException("老图删除失败！");
        }
        String imageKey = qiniuService.buildImageKey();
        goodsService.updateCoverImage(id, imageKey);
        return AjaxQiniuMessage.newSuccess(imageKey, AjaxMessage.newSuccessMsg(imageKey)).toJsonString();
    }

    /**
     * 添加该商品的库存数量
     *
     * @param id
     * @param number
     * @return
     */
    @PostMapping("/{id}/addNumber")
    @PreAuthorize("hasRole('ROLE_SALE')")
    @ResponseBody
    public Object addNumber(@PathVariable("id") long id, long number) {
        goodsService.addNumber(id, number);
        return AjaxMessage.newSuccessMsg();
    }

    /**
     * 减少该商品的库存数量
     *
     * @param id
     * @param number
     * @return
     */
    @PostMapping("/{id}/reduceNumber")
    @PreAuthorize("hasRole('ROLE_SALE')")
    @ResponseBody
    public Object reduceNumber(@PathVariable("id") long id, long number) {
        goodsService.reduceNumber(id, number);
        return AjaxMessage.newSuccessMsg();
    }

    /**
     * 上架
     *
     * @param id
     * @return
     */
    @PostMapping("/{id}/shelves")
    @PreAuthorize("hasRole('ROLE_SALE')")
    @ResponseBody
    public Object shelves(@PathVariable("id") long id) {
        Goods goods = new Goods();
        goods.setId(id);
        goods.setStatus(GoodsStatusEnum.SHELVES.getValue());
        goodsService.update(goods);
        return AjaxMessage.newSuccessMsg();
    }

    /**
     * 下架
     *
     * @param id
     * @return
     */
    @PostMapping("/{id}/offShelves")
    @PreAuthorize("hasRole('ROLE_SALE')")
    @ResponseBody
    public Object offShelves(@PathVariable("id") long id) {
        Goods goods = new Goods();
        goods.setId(id);
        goods.setStatus(GoodsStatusEnum.OFF_SHELVES.getValue());
        goodsService.update(goods);
        return AjaxMessage.newSuccessMsg();
    }
}
